package top.huhuiyu.teachproject.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.huhuiyu.teachproject.anno.BucketLimit;
import top.huhuiyu.teachproject.anno.Limit;
import top.huhuiyu.teachproject.entity.AuthInfo;
import top.huhuiyu.teachproject.service.LimitService;
import top.huhuiyu.teachproject.service.RedisService;
import top.huhuiyu.teachproject.utils.AuthInfoUtils;

@Service
@Slf4j
@RequiredArgsConstructor
public class LimitServiceImpl implements LimitService {
  private final RedisService redisService;

  @Override
  public boolean checkLimit(Limit limit) {
    AuthInfo authInfo = AuthInfoUtils.authInfo();
    // 处理限流的key
    String key = String.format("%s_%s", authInfo.getIp(), limit.key());
    // 查看是否带有限流信息
    if (redisService.hasKey(key)) {
      return false;
    }
    // 保存限流信息
    redisService.save(key, "1", limit.timeout() * 1000L);
    return true;
  }

  @Override
  public boolean checkLimit(BucketLimit limit) {
    // 处理限流的key
    String key = String.format("bucket_limit_%s", limit.key());
    // 数据不存在的情况
    if (!redisService.hasKey(key)) {
      redisService.save(key, 1, limit.timeout() * 1000L);
      return true;
    }
    // 数据存在的情况
    Integer value = redisService.get(key, Integer.class);
    value++;
    if (value > limit.limit()) {
      return false;
    }
    redisService.update(key, value);
    return true;
  }


}
